//
//  MYGSelectAllDorctorsViewController.swift
//  MYDoctor
//
//  Created by 王振明 on 2024/4/28.
//

import UIKit
import JXSegmentedView
import MJRefresh

class MYGSelectAllDorctorsViewController: UIViewController {
    var patientArr:[String:[MYGFriendModel]] = [:]
    var titleArr:[String] = []
    var contentArr:[[MYGFriendModel]] = []
//    var patientType:Int = 1
    var isMyFriend = true
    var oldArr:[MYGFriendModel] = []
    var caseModel:MYGCaseClasmListModel?
    var selectDoc:MYGFriendModel = MYGFriendModel()
    var allDoctorPage:Int = 1
    var friendsPage:Int = 1
    var screenStr:String = ""
    override func viewDidLoad() {
        super.viewDidLoad()
        print("abcd"["abcd".startIndex])
        initUI()
        getDatasource()
        NotificationCenter.default.addObserver(self, selector: #selector(screenAction), name: NSNotification.Name.init("patientScreen"), object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(reloadNewDatasource), name: NSNotification.Name.init("refreshMyPatientList"), object: nil)

    }
    
    @objc func screenAction(obj:Notification){
        let dic:[String:Any] = obj.object as? [String : Any] ?? [:]
        screenStr = dic["screenStr"] as? String ?? ""
        friendsPage = 1
        allDoctorPage = 1
        getDatasource()
//        let str:String = dic["screenStr"] as? String ?? ""
//        var filteredPeople = oldArr.filter { person in
//            person.name.contains(str)
//        }
//        if str.count == 0{
//            filteredPeople = oldArr
//        }
//        patientArr = [:]
//        titleArr.removeAll()
//        contentArr.removeAll()
//        groupByInitialLetter(people: filteredPeople)
    }
    private func initUI(){
        view.addSubview(patienttableView)
        patienttableView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
    }
    @objc func reloadNewDatasource(){
        patientArr = [:]
        titleArr.removeAll()
        contentArr.removeAll()
        oldArr.removeAll()
        getDatasource()
    }
    @objc private func getDatasource(){
        if isMyFriend{
            MYGNetwork<MYGMeAPI, MYGPageModel<MYGFriendModel>>.request(target: .myFriends(param: [
                "pageSize":"100",
                "page":friendsPage])) {[weak self] item in
                    if item.list.count > 0{
                        if self?.friendsPage == 1{
                            self?.oldArr = item.list
                        }else{
                            self?.oldArr.append(contentsOf: item.list)
                        }
                        self?.groupByInitialLetter(people: self?.oldArr ?? [])

                    }
                    self?.patienttableView.mj_footer?.endRefreshing()
                    self?.patienttableView.mj_header?.endRefreshing()
                } failed: { _, error in
                    MMYGHUD.showToast(text: error)
                    self.patienttableView.mj_footer?.endRefreshing()
                    self.patienttableView.mj_header?.endRefreshing()
                }
        }else{
            MMYGNetwork<MYGMessageApi, MYGPageModel<MYGFriendModel>>.request(target:.searchDoctor(kwd: screenStr, department: "", hospital: "", title: "",page: allDoctorPage)) { [weak self] item in
                if item?.list.count ?? 0 > 0{
                    if self?.allDoctorPage == 1{
                        self?.oldArr = item?.list ?? []
                    }else{
                        self?.oldArr.append(contentsOf: item?.list ?? [])
                    }
                    self?.groupByInitialLetter(people: self?.oldArr ?? [])

                }
                self?.patienttableView.mj_footer?.endRefreshing()
                self?.patienttableView.mj_header?.endRefreshing()
            } failed: { _, error in
                MYGLoading.hide()
                MMYGHUD.showToast(text: error)
                self.patienttableView.mj_footer?.endRefreshing()
                self.patienttableView.mj_header?.endRefreshing()
            }
        }

    }
    // 获取字符串的首字母拼音首字母
    //    func getFirstPinyinLetter(_ string: String) -> String {
    //        // 这里只是一个简化的示例，并不考虑多音字等情况
    //        let firstCharacter = string.prefix(1)
    //        let pinyin = firstCharacter.transformToPinYin()?.first // 假设你有一个扩展方法可以得到拼音
    //        return pinyin ?? firstCharacter
    //    }
    func transformToPinYin(str:String)->String{
        let mutableString = NSMutableString(string: str)
        CFStringTransform(mutableString, nil, kCFStringTransformToLatin, false)
        CFStringTransform(mutableString, nil, kCFStringTransformStripDiacritics, false)
        let string = String(mutableString)
        //        let resultStr:String = string.replacingOccurrences(of: " ", with: "")
        if str.count == 0{
            return "#"
        }
        if string.count == 0{
            let firstCharacter = str.first!
            return String(firstCharacter)
        }else{
            let firstCharacter = string.first!
            return String(firstCharacter)
        }
        // 输出：H
        
    }
    // 将数组按首字母拼音分组
    func groupByInitialLetter(people: [MYGFriendModel]){
        titleArr.removeAll()
        contentArr.removeAll()
        var grouped = [String: [MYGFriendModel]]()
        
        for person in people {
            let initialLetter = transformToPinYin(str: person.name)
            if grouped[initialLetter] == nil {
                grouped[initialLetter] = []
            }
            grouped[initialLetter]?.append(person)
        }
        var unsortedDictionary: [String: [MYGFriendModel]] = [:]
        let sortedDictionary22 = grouped.sorted(by: { $0.key < $1.key })
        for item in sortedDictionary22 {
            unsortedDictionary[item.key] = item.value
            titleArr.append(item.key)
            contentArr.append((item.value))
        }
        patientArr = unsortedDictionary
        patienttableView.reloadData()
    }
    lazy var patienttableView: UITableView = {
        let control = UITableView()
        control.showsVerticalScrollIndicator = false
        control.delegate = self
        control.dataSource = self
        control.rowHeight = UITableView.automaticDimension
        control.separatorStyle = .none
        control.register(cellWithClass: MYGSelectAllDorctorsTableViewCell.self)
        control.mj_header = MJRefreshNormalHeader(refreshingBlock: {[weak self] in
            self?.allDoctorPage = 1
            self?.friendsPage = 1
            self?.getDatasource()
        })
        control.mj_footer = MJRefreshAutoNormalFooter(refreshingBlock: {[weak self] in
            self?.allDoctorPage = self!.allDoctorPage + 1
            self?.friendsPage = self!.friendsPage + 1
            self?.getDatasource()
        })
        return control
    }()
}
extension MYGSelectAllDorctorsViewController:UITableViewDelegate,UITableViewDataSource {
    func numberOfSections(in tableView: UITableView) -> Int {
        return patientArr.count
    }
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 82.5
    }
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 30
    }
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let vi = UIView()
        let lab = UILabel()
        lab.text = titleArr[section]
        lab.font = .regular(19)
        lab.textColor = .rgba(5, 5, 5, 1)
        vi.addSubview(lab)
        lab.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(20)
            make.centerY.equalToSuperview()
            make.height.equalTo(20)
        }
        return vi
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        let arr:[MYGFriendModel] = contentArr[section]
        return arr.count
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withClass: MYGSelectAllDorctorsTableViewCell.self, for: indexPath)
        cell.selectionStyle = .none
        let arr:[MYGFriendModel] = contentArr[indexPath.section]
        cell.doctorModel = arr[indexPath.row]
        if cell.doctorModel.id == selectDoc.id{
            cell.selectBtn.isSelected = true
        }else{
            cell.selectBtn.isSelected = false
        }
        return cell
    }
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let arr:[MYGFriendModel] = contentArr[indexPath.section]
        
        selectDoc = arr[indexPath.row]
        tableView.reloadData()
//        let vc = MYGPatientDetailViewController()
//        let arr:[MYGFriendModel] = contentArr[indexPath.section]
//        vc.patientModel = arr[indexPath.row]
//        self.navigationController?.pushViewController(vc, animated: true)
    }
}

extension MYGSelectAllDorctorsViewController:JXSegmentedListContainerViewListDelegate {
    
    func listView() -> UIView {
        return view
    }
}
